Javascript Objects
Published on: July 03, 2021 By T.Andrew Rayan
Javascript Objects are used to store a collection of data. Usually a normal variable will store a single data. In order to store multiple data to a single variable we use objects.
Example
Here the 'employee' is an object variable, which store the multiple data of the employee and it can have different type of data like string, number, boolean etc.
Javascript object uses key-value pair to store data in it. In the above 'employee' object 'employeeName' is the key and 'Andrew' is the value to it. Similarly, we can have any number of key-value pair inside an object.
The keys of the object can be also called as properties of the object.
We have 2 ways to access the values of the properties of an object.
*) Dot notation
*) Bracket notation
Example
Output
Andrew Senior Developer
Both serves different scenario. If you know the property to access we can use both 'Dot' notation and 'Bracket' notation. Suppose you have the property as a string and dynamically get the value of the object we use 'Bracket' notation.
To assign the value to a property of an object anywhere in the program we can assign the value to the property as below
employee.salary = '7L';
To remove a propery from an object we can use delete keyword followed by the object name and its property with 'Dot' or 'Bracket' notation.
delete employee.dateOfJoining;
Its also possible to declare nested object to an object. Let me add the address property to the employee object.
Output
India
We can also add the function to object and access those functions with the object name.
Output
Welcome Andrew
Here we have created a function with name 'greetMessage' and had called the function with 'dot' notation.